package com.tang.boot.boot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tang.boot.boot.domain.Book;
import com.tang.boot.boot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result insert(@RequestBody Book book) {
        Boolean sign = bookService.insert(book);
        if (sign){
            return new Result(Code.INERT_OK, sign);
        }else{
            return new Result(Code.INERT_ERR, sign);
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        Boolean sign = bookService.delete(id);
        return new Result(sign ? Code.DELETE_OK : Code.DELETE_ERR, sign);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        Boolean sign = bookService.update(book);
        return new Result(sign ? Code.UPDATE_OK : Code.UPDATE_ERR, sign);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Integer id) {
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String message = "";
        if (book == null){
            message = "数据查询失败，请重试！";
        }
        return new Result(code, book, message);
    }

    @GetMapping
    public Result getAll() {
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String message = bookList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, bookList, message);
    }

    @GetMapping("{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize, Book book){
        IPage<Book> page = bookService.getPage(currentPage, pageSize, book);
        // 如果当前页码值大于总页码值，和选择最大的页码作为显示页
        if (currentPage > page.getPages()){
            page = bookService.getPage((int)page.getCurrent(), pageSize, book);
        }
        Integer code = page != null ? Code.GET_OK : Code.GET_ERR;
        String message = page != null ? "" : "数据查询失败，请重试！";
        System.out.println(book);
        return new Result(code, page, message);
    }
}
